package com.robot.service.impl;


import cn.hutool.core.date.DateTime;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import com.robot.common.enums.CompanyTypeEnum;
import com.robot.common.enums.IntegralTypeEnum;
import com.robot.common.enums.ResponseEnum;
import com.robot.common.enums.RoleCodeEnum;
import com.robot.common.exception.BusinessException;

import com.robot.common.utils.DateFullUtils;
import com.robot.common.utils.ShuffleCodeUtils;
import com.robot.dao.dto.CompanyDTO;

import com.robot.dao.dto.CompanyPageDTO;
import com.robot.dao.dto.UserDTO;
import com.robot.dao.entity.Company;
import com.robot.dao.entity.Integral;
import com.robot.dao.entity.IntegralLog;
import com.robot.dao.entity.User;
import com.robot.dao.mapper.CompanyMapper;
import com.robot.dao.mapper.IntegralLogMapper;
import com.robot.dao.mapper.IntegralMapper;
import com.robot.dao.mapper.UserMapper;
import com.robot.dao.vo.CompanyVO;
import com.robot.dao.vo.UserInfoVO;
import com.robot.service.CompanyService;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.C;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.List;

@Slf4j
@Service
public class CompanyServiceImpl implements CompanyService {


    @Autowired
    private CompanyMapper companyMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private IntegralMapper integralMapper;

    @Autowired
    private IntegralLogMapper integralLogMapper;


    @Override
    public String generateInvitationCode(CompanyDTO companyDTO) {
        Company company = companyMapper.selectByCode(companyDTO.getCompanyCode());
        if (ObjectUtils.isEmpty(company)) {
            throw new BusinessException(ResponseEnum.ILLEGAL_PARAMETER.getCode(), "未查询到该公司信息！");
        }
        String invitationCode = ShuffleCodeUtils.getRandomCode();
        company.setInvitationCode(invitationCode);
        companyMapper.updateById(company);

        return invitationCode;

    }


    @Override
    public PageInfo<UserInfoVO> pageCompanyUserList(CompanyPageDTO companyDTO) {
        PageHelper.startPage(companyDTO.getPage(), companyDTO.getPageSize());
        if (StringUtils.isEmpty(companyDTO.getCompanyCode())) {
            throw new BusinessException(ResponseEnum.ILLEGAL_PARAMETER.getCode(), "未传入企业编码！");
        }
        log.info("开始分页查询企业用户信息。。。。。。。");
        List<UserInfoVO> userInfoVOList = companyMapper.pageCompanyUserList(companyDTO);
        PageInfo<UserInfoVO> pageInfo = new PageInfo<>(userInfoVOList);
        return pageInfo;
    }


    @Override
    public CompanyVO createCompany(UserDTO userDTO) {

        if (ObjectUtils.isEmpty(userDTO.getUserId())) {
            throw new BusinessException(ResponseEnum.ILLEGAL_PARAMETER.getCode(), "请传入用户Id！");
        }
        if (StringUtils.isBlank(userDTO.getCompanyName())) {
            throw new BusinessException(ResponseEnum.ILLEGAL_PARAMETER.getCode(), "请设置企业名称！");
        }
        if (ObjectUtils.isEmpty(userDTO.getCompanyType())) {

            throw new BusinessException(ResponseEnum.ILLEGAL_PARAMETER.getCode(), "请设置企业类型（10-团队，11-企业）！");
        }
        User user = userMapper.selectById(userDTO.getUserId());
        if (ObjectUtils.isEmpty(user)) {
            throw new BusinessException(ResponseEnum.ILLEGAL_PARAMETER.getCode(), "未查询到用户信息！");
        }


        if (StringUtils.isNotBlank(user.getCompanyCode())) {
            if (user.getRoleCode().equals(RoleCodeEnum.COMPANY_USER.getCode())) {
                throw new BusinessException(ResponseEnum.ILLEGAL_PARAMETER.getCode(), "用户已加入企业！");
            }
            if (user.getRoleCode().equals(RoleCodeEnum.COMPANY_MANAGER.getCode())) {
                throw new BusinessException(ResponseEnum.ILLEGAL_PARAMETER.getCode(), "用户已存在管理员身份！");
            }
        }

        Company company =this.buildCompanyAndIntegral(user,userDTO);
        CompanyVO companyVO = new CompanyVO();
        BeanUtils.copyProperties(company, companyVO);
        return companyVO;

    }


    @Transactional
    public Company buildCompanyAndIntegral(User user,UserDTO userDTO){
        //TODO:时间格式工具类优化

        //新建积分账户
        Integral integral=Integral.builder()
                .startTime(DateTime.now())
                .endTime(DateFullUtils.addDate(DateTime.now(), 365))
                .build();

        if(userDTO.getCompanyType().equals(CompanyTypeEnum.TEAM.getCode())){
            integral.setIntegralScore(6000);
        }else if(userDTO.getCompanyType().equals(CompanyTypeEnum.ENTERPRISE.getCode())){
            integral.setIntegralScore(12000);
        }

        integralMapper.insert(integral);


        //新建公司
        Company company = Company.builder()
                .companyCode(user.getUserPhone())
                .companyName(userDTO.getCompanyName())
                .invitationCode(ShuffleCodeUtils.getRandomCode())
                .companyType(userDTO.getCompanyType())
                .integralId(integral.getId())
                .build();
        companyMapper.insert(company);

        user.setRoleCode(RoleCodeEnum.COMPANY_MANAGER.getCode());
        user.setCompanyCode(company.getCompanyCode());
        userMapper.updateById(user);


        //积分操作日志
        //TODO:抽出优化
        IntegralLog integralLog=IntegralLog.builder()
                .integralScore(integral.getIntegralScore())
                .type(IntegralTypeEnum.ADD.getCode())
                .userId(company.getId())
                .remark("企业新建积分账户")
                .build();
        integralLogMapper.insert(integralLog);

        return company;



    }


}
